﻿using System;
using System.Runtime.InteropServices;
using IServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;

namespace AzurePlugin.Converter
{
    public class ServiceProviderAdapter
    {
        private readonly IServiceProvider _serviceProvider;

        public ServiceProviderAdapter(object serviceProvider)
        {
            _serviceProvider = (IServiceProvider) serviceProvider;
        }

        public T GetService<T>() where T : class
        {
            T result = null;
            IntPtr serviceIntPtr;

            var sidGuid = typeof(T).GUID;
            var iidGuid = sidGuid;
            var code = _serviceProvider.QueryService(sidGuid, iidGuid, out serviceIntPtr);

            if (code != 0)
            {
                Marshal.ThrowExceptionForHR(code);
            }
            else if (!serviceIntPtr.Equals(IntPtr.Zero))
            {
                result = Marshal.GetObjectForIUnknown(serviceIntPtr) as T;
                Marshal.Release(serviceIntPtr);
            }

            return result;
        }
    }
}
